<template>
  <div id="add_book">
    <h2>添加图书</h2>
    <el-form class="add_form" ref="form" :model="newBookObj" label-width="80px" label-position="top">
      <el-form-item label="书籍名称">
        <el-input v-model="newBookObj.name"></el-input>
      </el-form-item>
      <el-form-item label="书籍作者">
        <el-input v-model="newBookObj.author"></el-input>
      </el-form-item>
      <el-form-item label="书籍库存">
        <el-input v-model="newBookObj.stock"></el-input>
      </el-form-item>
      <el-form-item label="书籍封面">
        <el-upload
            class="avatar-uploader"
            :action="`${baseUrl}/api/image/uploadImage`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess">
          <img v-if="newBookObj.cover" :src="newBookObj.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-button @click="addBook" type="primary">添加书籍</el-button>
    </el-form>
  </div>
</template>

<script>
import baseUrl from "../const/baseUrl";
import {addBook} from "../network/bookApi";

export default {
  name: "AddBook",
  data(){
    return{
      baseUrl,
      newBookObj:{
        cover:""
      }
    }
  },
  methods:{
    addBook(){
      addBook(this.newBookObj).then((result)=>{
        if (result.data.code===200){
          this.$message({
            message: '添加用户成功!',
            type: 'success'
          });
          sessionStorage.setItem("wlj-url", "/bookmanage");
          this.$router.push("/blankpage");
        }
      }).catch((reason)=>{
        console.log(reason);
      })
    },
    //头像上传成功
    handleAvatarSuccess(res){
      this.newBookObj.cover=res.data;
    },
  }
}
</script>

<style scoped>
.add_form{
  width: 70%;
  margin: 30px auto;
  text-align: left;
}
/*头像*/
.avatar{
  height: 150px;
}
</style>
